package cn.itcast.n4_共享模型_管程;

import java.util.ArrayList;

public class Test06_线程安全分析_将list改为局部变量且不暴露引用不会出现线程安全问题 {

    static final int THREAD_NUMBER = 2;
    static final int LOOP_NUMBER = 2000;

    public static void main(String[] args) {
        ThreadSafe1 test = new ThreadSafe1();
        for (int i = 0; i < THREAD_NUMBER; i++) {
            new Thread(() -> {
                test.method1(LOOP_NUMBER);
            }, "Thread" + (i + 1)).start();
        }
    }
}

class ThreadSafe1 {
    public final void method1(int loopNumber) {
        // 此时为局部变量
        ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < loopNumber; i++) {
            method2(list);
            method3(list);
        }
    }
    private void method2(ArrayList<String> list) {
        list.add("1");
    }
    private void method3(ArrayList<String> list) {
        list.remove(0);
    }
}



